package com.gxa.clientadmin.realm;


import com.gxa.clientadmin.mapper.AssignMapper;
import com.gxa.clientadmin.mapper.PermissionMaper;
import com.gxa.clientadmin.pojo.Admin;
import com.gxa.clientadmin.pojo.Assign;
import com.gxa.clientadmin.pojo.Permission;
import com.gxa.clientadmin.service.AdminService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;


public class CustomRealm extends AuthorizingRealm {

    @Resource
    AdminService adminService;
    
    @Resource
    AssignMapper assignMapper;
    
    
    @Resource
    PermissionMaper permissionMaper;

   /**
     * 授权信息配置
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String username = principalCollection.getPrimaryPrincipal().toString();
        // 通过username查询用户
        Admin admin = adminService.selectOne(username);
        Assign assign = new Assign();
        assign.setAId(admin.getId());
        List<Assign> select = assignMapper.select(assign);
        // 添加权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
       
            for (int i = 0; i < select.size(); i++) {
                Permission permission = permissionMaper.selectByPrimaryKey(select.get(i).getPId());
                simpleAuthorizationInfo.addStringPermission(String.valueOf(permission.getMenuid()));
            }
        
        return simpleAuthorizationInfo;
    }

   /**
     * 认证信息配置
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 认证主体为空,则返回null认证
        Object principal = authenticationToken.getPrincipal();
        if(StringUtils.isEmpty(principal))
            return null;
        //获取用户信息
        String username = principal.toString();
        Admin admin = adminService.selectOne(username);
        // 未查询到用户信息,返回null认证
        if(admin == null){
            return null;
        }else{
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,admin.getPassword(),getName());
            return simpleAuthenticationInfo;
        }
    }
}
